/**
 * 获取数据存储空间
 */
console.clear();
const Storage = storage.getDataStorage('Storage_players');
import i18next from 'i18next';

/**
 * 需要存储的变量
 */
const needSave = {
  level: 0,
  exp: 0,
  coin: 0,
  dz: {
    name: [],
    speed: [],
    jumpPower: [],
    acceleration: [],
  },
  useCar: {
    id: '',
    name: '',
  },
  cars: [],
  fastestRecord: 180,
  haspassed: false,
};
/**
 * 数据存储模块
 */
export class StorageAPI {
  /**
   * 获取玩家数据
   */
  static getPlayerData(entity: GamePlayerEntity): { [key: string]: JSONValue } {
    const data = { name: entity.player.name };
    for (const key in needSave) {
      console.log(key);
      Object.defineProperty(data, key, {
        value: entity[key as keyof GameEntity],
        writable: true,
        enumerable: true,
        configurable: true,
      });
    }

    return data;
  }

  /**
   * 储存玩家数据到数据库
   */
  static async savePlayer(entity: GamePlayerEntity): Promise<void> {
    if (!entity.player.userId) {
      return;
    }
    await Storage.update(entity.player.userId, () => {
      return StorageAPI.getPlayerData(entity);
    });
  }

  /**
   * 从数据库读取玩家数据并给玩家对应变量赋值
   */
  static async loadPlayer(entity: GamePlayerEntity): Promise<void> {
    Object.assign(entity, needSave); //先赋默认值，防止报错
    if (!entity.player.userId) {
      return;
    }
    let data = undefined;
    while (true) {
      try {
        data = await Storage.get(entity.player.userId);
        break;
      } catch (error) {
        console.log(error);
        return;
      }
    }
    if (data && data.value) {
      Object.assign(entity, data.value);
      entity.player.directMessage(
        i18next.t('Storagedata.loadPlayer', { lng: entity.language })
      );
    } else {
      Object.assign(entity, needSave);
      while (true) {
        try {
          await Storage.set(
            entity.player.userId,
            StorageAPI.getPlayerData(entity)
          );
          break;
        } catch (error) {
          console.log(error);
          return;
        }
      }
      entity.player.directMessage(
        i18next.t('Storagedata.createData', { lng: entity.language })
      );
      world.querySelectorAll('player').forEach((x) => {
        x.player.directMessage(
          i18next.t('Storagedata.welcome_firstEnter', {
            lng: entity.language,
            name: entity.player.name,
          })
        );
      });
    }
  }
}
